﻿using Helper;
using MessagePush;
using Newtonsoft.Json.Linq;
using System;
using System.Configuration;
using System.Data;
using System.Windows.Forms;

namespace cswWFServer
{

    public partial class FormZF : Form
    {
        private ClassDAL dal = null;
        public FormZF()
        {

            InitializeComponent();
        }
        //窗体关闭前发生事件
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //窗体关闭原因为单击"关闭"按钮或Alt+F4
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;           //取消关闭操作 表现为不关闭窗体
                this.Hide();               //隐藏窗体
            }
        }
        //"显示窗体"单击事件
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Show();                                //窗体显示
            this.WindowState = FormWindowState.Normal;  //窗体状态默认大小
            this.Activate();                            //激活窗体给予焦点
        }
        //"隐藏窗体"单击事件
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.Hide();                      //隐藏窗体
        }
        //"退出"单击事件
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            //点击"是(YES)"退出程序
            if (MessageBox.Show("确定要退出程序?", "安全提示",
                        System.Windows.Forms.MessageBoxButtons.YesNo,
                        System.Windows.Forms.MessageBoxIcon.Warning)
                == System.Windows.Forms.DialogResult.Yes)
            {
                notifyIcon1.Visible = false;   //设置图标不可见
                this.Close();                  //关闭窗体
                this.Dispose();                //释放资源
                Application.Exit();            //关闭应用程序窗体
            }
        }
        //鼠标左键图标事件
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            //点击鼠标"左键"发生
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;                        //窗体可见
                this.WindowState = FormWindowState.Normal;  //窗体默认大小
                this.notifyIcon1.Visible = true;            //设置图标可见
            }
        }
        //开始排查需要发短息的用户
        private void button1_Click(object sender, EventArgs e)
        {
            //1.申请开店信息审核未支付过期排查
            //2.合同过期排查


            textBox1.AppendText("系统开始运行10秒后检测:申请开店信息审核未支付过期的数据...\n");
            timer1.Start();

            label2.Text = "0";//第一次检测
            button1.Enabled = false;

        }
        //每24小时
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Interval = 86400000; //60*1000*60*24
            label2.Text = (int.Parse(label2.Text) + 1).ToString();
            int count = int.Parse(label2.Text);
            textBox1.AppendText("第" + count + "次检测..\n");

            //1.查询开店申请待支付今日需要发送的数据

            string sql = "select * from t_custom_sq where sqStatus='3'";//审核成功需要支付的数据
            DataSet dt = dal.Query(sql);

            if (dt.Tables[0] != null && dt.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                {
                    //是否发送
                    bool fasong = false;
                    //1.需要发送支付短信的
                    if (dt.Tables[0].Rows[i]["guoqiDate"] != null && dt.Tables[0].Rows[i]["guoqiDate"].ToString() != "")
                    {
                        string time1 = DateTime.Parse(dt.Tables[0].Rows[i]["guoqiDate"].ToString()).ToString("yyyy-MM-dd");
                        string time2 = DateTime.Now.ToString("yyyy-MM-dd");
                        if ((DateTime.Parse(time1) - DateTime.Parse(time2)).Days == 1)
                        {
                            //日志
                            textBox1.AppendText("用户:" + dt.Tables[0].Rows[i]["customId"].ToString() + "发送短信为:您的开店申请已审核通过，请在【2】个工作日内打款抢先入驻，谢谢!\n");
                            //发送短信到手机
                            fasong = SendSimMessage(dt.Tables[0].Rows[i]["phone"].ToString(), "您的开店申请已审核通过，请在【2】个工作日内打款抢先入驻，谢谢！");
                        }
                        else if ((DateTime.Parse(time1) - DateTime.Parse(time2)).Days == 0)
                        {
                            string time3 = (DateTime.Parse(time1) - DateTime.Parse(time2)).Days + "";
                            //日志
                            textBox1.AppendText("用户:" + dt.Tables[0].Rows[i]["customId"].ToString() + "发送短信为:您的开店申请已审核通过，请在今天23:59分前打款，否则将视为放弃开店资格！\n");
                            //发送短信到手机
                            fasong = SendSimMessage(dt.Tables[0].Rows[i]["phone"].ToString(), "您的开店申请已审核通过，请在今天23:59分前打款，否则将视为放弃开店资格！");

                        }
                        else if ((DateTime.Parse(time1) - DateTime.Parse(time2)).Days < 0)
                        {
                            //2.需要告知支付时间段过期，重新提交资料审核,并重新修改状态为“审核失败”，原因：已过支付期限，重新提交资料审核
                            textBox1.AppendText("用户:" + dt.Tables[0].Rows[i]["customId"].ToString() + "发送短信为:您的开店申请已审核通过，但已过支付期限，重新提交资料审核!\n");
                            //发送短信到手机
                            fasong = SendSimMessage(dt.Tables[0].Rows[i]["phone"].ToString(), "您的开店申请已审核通过，但已过支付期限，重新提交资料审核!");
                            //判断
                            if (fasong)
                            {
                                //修改状态为 审核失败
                                dal.ExecuteSql("update t_custom_sq set sqStatus=4,ziliaoYuanyin='1:您的开店申请已过支付期限，需重新提交资料审核!' where customId='" + dt.Tables[0].Rows[i]["customId"].ToString() + "'");
                            }
                        }
                        else
                        {
                            //当天的已经发过
                        }
                    }
                    else
                    {
                        textBox1.AppendText("用户:" + dt.Tables[0].Rows[i]["customId"].ToString() + "合同过期时间有误，请排查\n");
                    }
                    if (fasong)
                    {
                        label3.Text = (int.Parse(label3.Text) + 1).ToString();
                        ListViewItem item = new ListViewItem(new string[] { dt.Tables[0].Rows[i]["customId"].ToString(), dt.Tables[0].Rows[i]["name"].ToString(), dt.Tables[0].Rows[i]["phone"].ToString(), dt.Tables[0].Rows[i]["guoqiDate"].ToString(), "申请开店支付" });
                        this.listView1.Items.Insert(0, item);
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
            //2.开始查询合同是否快过期 72小时内就发送

            string sql1 = "select *,b.num from t_custom_sq a  left join TB_taocan b on a.taocanId=b.id where a.sqStatus='6' and a.address not like'%体验%'";//查看合同是否过期
            DataSet dt1 = dal.Query(sql1);

            if (dt1.Tables[0] != null && dt1.Tables[0].Rows.Count > 0)
            {

                for (int i = 0; i < dt1.Tables[0].Rows.Count; i++)
                {
                    if (dt1.Tables[0].Rows[i]["zhtAdress"] != null && dt1.Tables[0].Rows[i]["zhtAdress"].ToString() != "")
                    {
                        try
                        {
                            //年限
                            int startDay = int.Parse(dt1.Tables[0].Rows[i]["num"].ToString());

                            string zhtAdress = dt1.Tables[0].Rows[i]["zhtAdress"].ToString();
                            zhtAdress = zhtAdress.Substring(zhtAdress.IndexOf("?") + 1, zhtAdress.Length - (zhtAdress.IndexOf("?") + 1));
                            string date = zhtAdress.Split('&')[4].Split('=')[1];


                            //string httime2 = DateTime.Parse(date).AddYears(startDay) + "";
                            //if ((DateTime.Now - DateTime.Parse(date)).Days >= startDay * 360 && (DateTime.Now - DateTime.Parse(date)).Days <= startDay * 360 + 6)
                            //{
                            if (DateTime.Parse(date).AddYears(startDay) < DateTime.Parse(DateTime.Now.AddDays(7).ToString("yyyy-MM-dd") + " 00:00:00") && DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00") <= DateTime.Parse(date).AddYears(startDay))
                            {
                                string Ydate = DateTime.Parse(date).AddYears(startDay).ToString("yyyy-MM-dd");
                                //日志
                                textBox1.AppendText("用户:" + dt1.Tables[0].Rows[i]["customId"].ToString() + "发送短信为:您的合同截止，【" + Ydate + "】终止。请及时联系中国超市网更换！\n");
                                //发送短信到手机
                                bool fasong = SendSimMessage(dt1.Tables[0].Rows[i]["phone"].ToString(), "您的合同截止，【" + Ydate + "】终止。请及时联系中国超市网更换！");
                                //判断
                                if (fasong)
                                {
                                    label3.Text = (int.Parse(label3.Text) + 1).ToString();
                                    ListViewItem item = new ListViewItem(new string[] { dt1.Tables[0].Rows[i]["customId"].ToString(), dt1.Tables[0].Rows[i]["name"].ToString(), dt1.Tables[0].Rows[i]["phone"].ToString(), dt1.Tables[0].Rows[i]["guoqiDate"].ToString(), "申请开店合同" });
                                    this.listView1.Items.Insert(0, item);
                                    System.Threading.Thread.Sleep(100);
                                }

                            }

                        }
                        catch (Exception ex)
                        {

                            textBox1.AppendText("用户:" + dt1.Tables[0].Rows[i]["customId"].ToString() + "合同过期时间有问题，请排查\n");
                        }
                    }
                    else
                    {
                        textBox1.AppendText("用户:" + dt1.Tables[0].Rows[i]["customId"].ToString() + "合同地址有问题，请排查\n");
                    }
                }
            }

        }
        public string GetReturn(string uriStr, string postData)
        {
            System.Net.WebClient clinet = new System.Net.WebClient();
            //打开URL，GET参数以URL后缀的方式就可以传递过去。
            System.IO.Stream stream = clinet.OpenRead(uriStr + postData);
            //把从HTTP中返回的流读为string
            System.IO.StreamReader reader = new System.IO.StreamReader(stream);
            string result = reader.ReadToEnd();

            return result;
        }
        //扫描数据库
        private void button2_Click(object sender, EventArgs e)
        {
            //1.订单下单时间超过30分钟未付款 修改为取消状态
            //2.订单收货时间或评价时间 距离现在7天以上 修改为已完成
            textBox2.AppendText("系统开始运行10秒后扫描:订单数据...\n");
            timer2.Start();
            label5.Text = "0";//第一次扫描
            button2.Enabled = false;


        }
        //每一分钟开始扫描
        private void timer2_Tick(object sender, EventArgs e)
        {
            timer2.Interval = 60 * 1000;//一分钟
            label5.Text = (int.Parse(label5.Text) + 1).ToString();
            int count = int.Parse(label5.Text);
            textBox2.AppendText("第" + count + "次检测..\n");

            //下单时间超过30分钟未付款 
            string sql = "select * from t_order where zt='1'";
            DataSet dt = dal.Query(sql);
            if (dt.Tables[0] != null && dt.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                {
                    //是否修改
                    bool updateFlag = false;
                    //1.需要修改
                    if (dt.Tables[0].Rows[i]["pudate"] != null && dt.Tables[0].Rows[i]["pudate"].ToString() != "")
                    {
                        if ((DateTime.Now - DateTime.Parse(dt.Tables[0].Rows[i]["pudate"].ToString())).Minutes > 29)
                        {
                            updateFlag = true;
                            SendMessage(dt.Tables[0].Rows[i]["customId"].ToString(), "订单取消", "您的订单:" + dt.Tables[0].Rows[i]["orderId"].ToString() + "超过30分钟未付款已被取消。");
                            textBox2.AppendText("用户:" + dt.Tables[0].Rows[i]["customId"].ToString() + "订单已经取消并发推送消息\n");
                            dal.Execute("update t_order set zt='8',customOrderDel=CONVERT(nvarchar(10),GETDATE(),121) where orderId='" + dt.Tables[0].Rows[i]["orderId"].ToString() + "'");
                        }
                    }
                    //需要修改/处理
                    if (updateFlag)
                    {
                        label5.Text = (int.Parse(label5.Text) + 1).ToString();
                        System.Threading.Thread.Sleep(100);
                    }
                }

            }
            //订单收货时间或评价时间 距离现在7天以上 修改为已完成 
            string sql1 = "select * from t_order where zt='3'or zt='4'";
            DataSet dt1 = dal.Query(sql1);
            if (dt1.Tables[0] != null && dt1.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dt1.Tables[0].Rows.Count; i++)
                {
                    //是否修改
                    bool updateFlag = false;
                    //1.需要修改  取确认收货时间
                    if (dt1.Tables[0].Rows[i]["shAffirmDate"] != null && dt1.Tables[0].Rows[i]["shAffirmDate"].ToString() != "")
                    {
                        //shAffirmDate
                        int num = (DateTime.Now - DateTime.Parse(dt1.Tables[0].Rows[i]["shAffirmDate"].ToString())).Days;
                        if ((DateTime.Now - DateTime.Parse(dt1.Tables[0].Rows[i]["shAffirmDate"].ToString())).Days > 7)
                        {
                            updateFlag = true;
                            SendMessage(dt1.Tables[0].Rows[i]["customId"].ToString(), "订单已完成", "您的订单:" + dt1.Tables[0].Rows[i]["orderId"].ToString() + "已完成,祝您购物愉快。");
                            textBox2.AppendText("用户:" + dt1.Tables[0].Rows[i]["customId"].ToString() + "订单修改为已完成并发推送消息\n");
                            dal.Execute("update t_order set zt='7' where orderId='" + dt1.Tables[0].Rows[i]["orderId"].ToString() + "'");


                        }
                    }
                    //需要修改/处理
                    if (updateFlag)
                    {
                        label5.Text = (int.Parse(label5.Text) + 1).ToString();
                        System.Threading.Thread.Sleep(100);
                    }
                }

            }
            //是否是23点59分
            if (DateTime.Now.ToString("HH:mm") == "23:59")
            {
                button4_Click(sender, e);
            }
            //是否是00点01分
            if (DateTime.Now.ToString("HH:mm") == "00:05")
            {
                button5_Click(sender, e);
            }
            ////是否是00点01分
            //if (DateTime.Now.ToString("HH:mm") == "10:30")
            //{
            //    button6_Click(sender, e);
            //}

            //是否是11点00分
            if (DateTime.Now.ToString("HH:mm") == "11:00")
            {
                button7_Click(sender, e);
            }
        }

        //发推送消息
        private void SendMessage(string customId, string title, string msg)
        {
            //插入一条消息
            // dal.Execute("insert into t_message(id,title,memo,pudate,customId) values('" + Guid.NewGuid().ToString() + "','" + title + "','" + msg + "',convert(nvarchar(19),GETDATE(),121),'" + customId + "')");
            //发送消息
            try
            {
                DataSet dscc = dal.getDataSet("select * from t_custom where customId='" + customId+"'");
                if (dscc.Tables[0] != null && dscc.Tables[0].Rows.Count > 0)
                {
                    //推送消息

                    string msgs = UMessageStr.msg;
                    UMessage u = JsonHelper.ParseFormJson<UMessage>(msgs);
                    u.sAvatar = dscc.Tables[0].Rows[0]["img"].ToString();
                    u.sCustomId = customId;
                    u.sName = dscc.Tables[0].Rows[0]["nicheng"].ToString();
                    u.status = "1";
                    u.msgTime = UDateTime.ConvertDateTimeInt(DateTime.Now).ToString();
                    string[] str = msg.Split('*');
                    if (str != null && str != null)
                    {
                        if (str.Length > 1)
                        {
                            u.content.img = str[1];
                            u.content.texts = str[0];
                        }
                        else
                        {
                            u.content.texts = str[0];
                        }
                    }
                    u.type1 = "1";
                    u.type2 = "2";
                    u.bussCode = "";
                    //string serverHtml3 = "http://getui.vx818.com/index.aspx?";
                    //string strUrl3 = "zt=" + dscc.Tables[0].Rows[0]["cidLx"].ToString() + "&appid=" + ConfigurationManager.AppSettings["gtappid"] + "&appkey=" + ConfigurationManager.AppSettings["gtappkey"] + "&mastersecret=" + ConfigurationManager.AppSettings["mastersecret"] + "&cid=" + dscc.Tables[0].Rows[0]["cid"].ToString() + "&mes=" + msg + "";
                    //string name3 = GetReturn(serverHtml3, strUrl3);
                    PushMessage.PushMessageToSingle(dscc.Tables[0].Rows[0]["cid"].ToString(), title, msg, JsonHelper.GetJson(u), "", "", dscc.Tables[0].Rows[0]["cidLx"].ToString());
                    //插入一条消息
                    addMessage(u);
                }

            }
            catch (Exception ex)
            {

            }
        }
        //把消息插入数据库
        private int addMessage(UMessage u)
        {
            int ret = 0;
            string sql = "insert into TB_message(fCustomId,fName,fAvatar,sCustomId,sAvatar,sName,msgTime,msgRedtime,type1,type2,bussCode,status,texts,msgType,img)" +
           " values('" + u.fCustomId + "','" + u.fName + "','" + u.fAvatar + "','" + u.sCustomId + "','" + u.sAvatar + "','" + u.sName + "','"
           + u.msgTime + "','" + u.msgRedtime + "','" + u.type1 + "','" + u.type2 + "','" + u.bussCode + "','" + u.status + "','"
           + u.content.texts + "','" + u.content.msgType + "','" + u.content.img + "')";
            //执行
            ret = dal.Execute(sql);
            return ret;
        }
        //发送手机短线
        private bool SendSimMessage(string phone, string msg)
        {
            bool fasong = false;
            //发送短信到手机
            string serverHtml = "http://106.ihuyi.cn/webservice/sms.php?";
            string strUrl = "method=Submit&account=" + ConfigurationManager.AppSettings["account"] + "&password=" + ConfigurationManager.AppSettings["password"] + "&mobile=" + phone + "&content=" + msg + "";
            string name = GetReturn(serverHtml, strUrl);

            if (name.IndexOf("提交成功") != -1)
            {
                fasong = true;
            }
            return fasong;
        }
        //开始扫描商户库存
        private void button3_Click(object sender, EventArgs e)
        {
            textBox3.AppendText("系统开始运行10秒后扫描:商户库存数据...\n");
            timer3.Start();
            label7.Text = "0";//第一次扫描
            button3.Enabled = false;
        }
        //每60分钟扫描商户库存
        private void timer3_Tick(object sender, EventArgs e)
        {
            timer3.Interval = 60 * 60 * 1000;//一分钟
            label7.Text = (int.Parse(label7.Text) + 1).ToString();
            int count = int.Parse(label7.Text);
            textBox3.AppendText("第" + count + "次检测..\n");

            //所有商户库存
            string sql = "select * from t_goods a left join t_users b  on a.usesrId= b.usersId where a.goodsId not like '%tiyan%' and a.kcNum=0  and  a.usesrId='1'  and a.delZt='1' and a.sjZt='1' ";
            DataSet dt = dal.Query(sql);
            if (dt.Tables[0] != null && dt.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                {
                    SendMessage(dt.Tables[0].Rows[i]["customId"].ToString(), "库存预警", "您的商品:" + dt.Tables[0].Rows[i]["title"].ToString() + "库存不足，请及时补充.");
                    textBox3.AppendText("商品:" + dt.Tables[0].Rows[i]["title"].ToString() + "库存不足，请及时补充.\n");
                }
            }
        }
        //每天23点扫描卡片信息
        private void button4_Click(object sender, EventArgs e)
        {
            if (label9.Text == "0")
            {
                textBox4.AppendText("系统开始运行10秒后扫描:卡片数据...\n");
                timer4.Start();
                label9.Text = "0";//第一次扫描
                button4.Enabled = false;
            }
        }
        //每天23点扫描卡片信息
        private void timer4_Tick(object sender, EventArgs e)
        {
            timer4.Interval = 24 * 60 * 60 * 1000;//每天
            label9.Text = (int.Parse(label9.Text) + 1).ToString();
            int count = int.Parse(label9.Text);
            textBox4.AppendText("第" + count + "次检测..\n");

            //未领取的
            string sql = "update TB_kpInfo set status=1 where endDate='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and status =2";
            dal.Execute(sql);
            //未使用的 
            string sql1 = " update TB_myCrad set status=3 where status=1 and kpId in( select bussCode from TB_kpInfo where endDate='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and status =3)";
            dal.Execute(sql1);
            //已领取的
            string sql2 = "update TB_kpInfo set status=1 where endDate='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and status =3";
            dal.Execute(sql2);
        }

        private void FormZF_Load(object sender, EventArgs e)
        {
            dal = new ClassDAL();
        }
        //每天21点发送统计信息
        private void button5_Click(object sender, EventArgs e)
        {
            if (label11.Text == "0")
            {
                textBox5.AppendText("系统开始运行10秒后扫描:统计数据...\n");
                timer5.Start();
                label11.Text = "0";//第一次扫描
                button5.Enabled = false;
            }
        }
        //每天00:05点发送统计信息
        private void timer5_Tick(object sender, EventArgs e)
        {
            timer5.Interval = 24 * 60 * 60 * 1000;//每天
            label11.Text = (int.Parse(label11.Text) + 1).ToString();
            int count = int.Parse(label11.Text);
            textBox5.AppendText("第" + count + "次检测..\n");

            string startDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")+" 00:00:00";
            string endDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")+" 23:59:59";

            //买单笔数
            string mdbs = dal.Query("select count(1) as mdbs from t_shop_moneyLog where zt=1 and (memo not like '订单号%' and memo not like '%提现失败%') and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["mdbs"].ToString();
            string mdAmount = dal.Query("select (case when sum(money) is null then 0 else sum(money) end)  as mdAmount from t_shop_moneyLog where zt=1 and (memo not like '订单号%' and memo not like '%提现失败%') and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["mdAmount"].ToString();
            //购买商品
            string gmbs = dal.Query("select count(1) as gmbs from t_shop_moneyLog where zt=1 and memo like '订单号%'  and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["gmbs"].ToString();
            string gmAmount = dal.Query("select (case when sum(money) is null then 0 else sum(money) end)  as gmAmount from t_shop_moneyLog where zt=1 and memo  like '订单号%'  and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["gmAmount"].ToString();
            //新用户注册
            string yhcount = dal.Query("select count(1) as yhcount from t_custom where pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["yhcount"].ToString();
            //商户注册
            string shcount = dal.Query("select count(1) as shcount from t_users where pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["shcount"].ToString();
            //充值
            string czbs = dal.Query("select count(1) as czbs from t_custom_money_log where lx=1  and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["czbs"].ToString(); ;
            string czAmount = dal.Query("select (case when sum(cast(money as decimal(18, 2))) is null then 0 else sum(cast(money as decimal(18, 2))) end)  as czAmount from t_custom_money_log where lx=1  and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["czAmount"].ToString();

            //提现
            string txbs = dal.Query("select count(1) as txbs from t_shop_moneyLog where zt=2  and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["txbs"].ToString(); ;
            string txAmount = dal.Query("select (case when sum(money) is null then 0 else sum(money) end)  as txAmount from t_shop_moneyLog where zt=2  and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["txAmount"].ToString();
            //退单
            string tdbs = dal.Query("select count(1) as tdbs from t_shop_moneyLog where zt=3  and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["tdbs"].ToString(); ;
            string tdAmount = dal.Query("select (case when sum(money) is null then 0 else sum(money) end)  as tdAmount from t_shop_moneyLog where zt=3  and pudate >='" + startDate + "' and pudate <='" + endDate + "'").Tables[0].Rows[0]["tdAmount"].ToString();

            string customId = "100010";
            string title = "监控统计";
            string msg = "昨日买单" + mdbs + "笔共" + mdAmount + "元,购买商品" + gmbs + "笔" + gmAmount + "元，新用户注册" + yhcount + "个商户注册" + shcount + "个，充值" + czbs + "笔" + czAmount + "元，申请提现" + txbs + "笔" + txAmount + "元，退单" + tdbs + "笔" + tdAmount + "元";
            SendMessage(customId, title, msg);
            SendMessage("100002", title, msg);
        }

        //每天10点30分发红包
        private void button6_Click(object sender, EventArgs e)
        {
            if (label13.Text == "0")
            {
                textBox6.AppendText("系统开始运行10秒后扫描:统计数据...\n");
                timer6.Start();
                label13.Text = "0";//第一次扫描
                button6.Enabled = false;
            }
        }
        //每天10点30分发红包
        private void timer6_Tick(object sender, EventArgs e)
        {
            timer6.Interval = 24 * 60 * 60 * 1000;//每天
            label13.Text = (int.Parse(label13.Text) + 1).ToString();
            int count = int.Parse(label13.Text);
            textBox6.AppendText("第" + count + "次检测..\n");

            string startDate = DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd") + " 00:00:00";
            string endDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59";

            double money = 0;
            string customId = "";
            string phone = "";
            string name = "";
            DataTable dt = dal.Query(@"select b.phone,a.money,a.psfee,a.customId,u.name from t_order a
                        left join t_custom b on a.customId = b.customId  left join t_users u on a.sjId=u.usersId
                        where a.pudate>='" + startDate + "' and   a.pudate<='" + endDate + "' and a.zt !=1 and a.zt!=8 order by a.pudate desc ").Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {

                //订单金额
                money = double.Parse(dt.Rows[i]["money"].ToString() ?? "0") - double.Parse(dt.Rows[i]["psfee"].ToString() ?? "0");
                customId = dt.Rows[i]["customId"].ToString();
                phone = dt.Rows[i]["phone"].ToString();
                name = dt.Rows[i]["name"].ToString();
                //订单返还红包编码
                string bussCodes = "ddhb" + Guid.NewGuid().ToString();
                //福气包来源 
                //dal.Execute("insert into TB_fuqibao(customId,lx,pudate,money,bussCode) values('" + customId + "','6',convert(nvarchar(19),GETDATE(),121),'" + double.Parse((money * 0.015 / 7).ToString("0.00")) + "','" + bussCodes + "')");
                ////增加福气总额
                //dal.Execute("update t_custom set fuqibaoMoney=fuqibaoMoney+" + double.Parse((money*0.015/7).ToString("0.00")) + " where customId='" + customId + "'");
                ////福气包 记录  未领取
                //string fuqibao_zq_code = "ddhb" + Guid.NewGuid().ToString();
                //dal.Execute("insert into TB_fuqibao_zq(code,customId,lx,money,pudate,title,bussCode) values('" + fuqibao_zq_code + "','" + customId + "','2','" + double.Parse((money * 0.015 / 7).ToString("0.00")) + "',convert(nvarchar(19),GETDATE(),121),'订单返还红包','" + bussCodes + "');");
                money = double.Parse((money * 0.015 / 7).ToString("0.00"));
                if (money > 0)
                {
                    string date = DateTime.Now.ToString("yyyy-MM-dd");
                    string skc = dal.Query(@"select count(1) as num from TB_h5hb where types=3 and phone='" + phone + "' and createTime >='" + (date + " 00:00:00") + "' and createTime<='" + (date + " 23:59:59") + "'").Tables[0].Rows[0]["num"].ToString();
                    if (skc == "0")
                    {
                        dal.Execute("insert into TB_h5hb(code,types,createTime,fee,phone,status,remarks) values('" + bussCodes + "',3,convert(nvarchar(19),GETDATE(),121),'" + money + "','" + phone + "',2,'订单返还红包')");
                        SendMessage(customId, name, "给您发红包了赶紧去领取吧！");
                    }
                }
            }
        }
        //每天11点00对账
        private void button7_Click(object sender, EventArgs e)
        {
            if (label15.Text == "0")
            {
                textBox7.AppendText("系统开始运行10秒后对账监控...\n");
                timer7.Start();
                label15.Text = "0";//第一次扫描
                button7.Enabled = false;
            }
        }
        //每天11点00对账
        private void timer7_Tick(object sender, EventArgs e)
        {
            timer7.Interval = 24 * 60 * 60 * 1000;//每天
            label15.Text = (int.Parse(label15.Text) + 1).ToString();
            int count = int.Parse(label15.Text);

            wxpaydz(DateTime.Now.AddDays(-1).ToString("yyyyMMdd"), count);
            alipaydz(DateTime.Now.AddDays(-1).ToString("yyyyMMdd"), count);
        }
        //微信对账
        private void wxpaydz(string date, int count)
        {

            string data = "date=" + date + "&type=wxpay&sign=" + PayHelp.GetDownLoadSignString(date, "wxpay", "zgcsw218zxcv") + "";
            string jsonData = PayHelp.HttpGet("http://pay.zgcsapp.com/DownloadBillpage.aspx", data);
            JObject obj = JObject.Parse(jsonData);
            string result = "";
            if (obj != null)
            {
                if (obj.Value<string>("code") == "1000")
                {
                    result = obj.Value<object>("data").ToString();

                    #region 微信
                    if (result.IndexOf("error_code") == -1)
                    {
                        string[] rst = result.Replace("\r\n", "#").Split('#');

                        //3开头的是 百富机器支付宝支付 
                        //4开头的是 百富机器微信支付
                        string tradeNoStr = "";
                        for (int i = 0; i < rst.Length; i++)
                        {
                            if (i > 0 && i < rst.Length - 2)
                            {
                                string[] dom = rst[i].Split(',');
                                string tradeNo = dom[6].Substring(1, dom[6].Length - 1);
                                if (tradeNo.Substring(0, 1) == "4")
                                {
                                    tradeNoStr += tradeNo + ",";
                                }
                            }
                            else
                            {
                                //标题处理
                            }
                        }

                        if (tradeNoStr.Length != 0)
                        {
                            tradeNoStr = tradeNoStr.Substring(0, tradeNoStr.Length - 1);
                            //云
                            int c = (tradeNoStr.Split(',').Length);

                            //本地
                            string sql = "select * from t_shop_moneyLog where zt='1' and shopId !='1' and pudate >='" + date + " 00:00:00" + "' and  pudate <='" + date + " 23:59:59" + "' and left(tradeNo,1)='4'";
                            DataTable dt = dal.getDataSet(sql).Tables[0];
                            int bdCount = 0;
                            if (dt != null)
                            {
                                bdCount = dt.Rows.Count;
                            }
                            //记录对不上 报警
                            if (c != bdCount)
                            {
                                textBox7.AppendText("第" + count + "次微信对账记录不一致..已发短信\n");
                                //发短信
                                SendSimMessage("13299021002", "检测到昨日百富微信支付记录与系统不一致！");
                                SendSimMessage("13989767654", "检测到昨日百富微信支付记录与系统不一致！");
                                SendMessage("100010", "微信对账不正常", "检测到昨日百富微信支付记录与系统不一致！");
                                SendMessage("100002", "微信对账不正常", "检测到昨日百富微信支付记录与系统不一致！");
                            }
                            else
                            {
                                textBox7.AppendText("第" + count + "次微信对账记录一致..\n");
                            }

                        }
                        else
                        {
                            textBox7.AppendText("第" + count + "次微信对账单没有记录..\n");
                        }

                    }

                    #endregion
                }
                else
                {
                    textBox7.AppendText("第" + count + "次微信对账异常..\n");
                    //发短信
                    SendSimMessage("13299021002", "百富微信对账监控异常，请手动查询昨日记录！");
                    SendSimMessage("13989767654", "百富微信对账监控异常，请手动查询昨日记录！");
                    SendMessage("100010", "微信对账异常", "百富微信对账监控异常，请手动查询昨日记录！");
                    SendMessage("100002", "微信对账异常", "百富微信对账监控异常，请手动查询昨日记录！");
                }
            }
            else
            {
                textBox7.AppendText("第" + count + "次微信对账出错..\n");
                //发短信
                SendSimMessage("13299021002", "百富微信对账监控出错，请手动查询昨日记录！");
                SendSimMessage("13989767654", "百富微信对账监控出错，请手动查询昨日记录！");
                SendMessage("100010", "微信对账出错", "百富微信对账监控出错，请手动查询昨日记录！");
                SendMessage("100002", "微信对账出错", "百富微信对账监控出错，请手动查询昨日记录！");
            }
        }
        private void alipaydz(string date, int count)
        {
            string data = "date=" + date + "&type=alipay&sign=" + PayHelp.GetDownLoadSignString(date, "alipay", "zgcsw218zxcv") + "";
            string jsonData = PayHelp.HttpGet("http://pay.zgcsapp.com/DownloadBillpage.aspx", data);
            JObject obj = JObject.Parse(jsonData);
            string result = "";
            if (obj != null)
            {
                if (obj.Value<string>("code") == "1000")
                {
                    result = obj.Value<object>("data").ToString();

                    #region 支付宝

                    string ms = PayHelp.DownloadNet(result, System.AppDomain.CurrentDomain.BaseDirectory + @"Download\", "alipay_" + date + ".csv.zip");
                    //解压 ms 
                    PayHelp.UnZip(ms, System.AppDomain.CurrentDomain.BaseDirectory + @"Download\alipay_" + date + ".csv");

                    //读取文件
                    ms = System.AppDomain.CurrentDomain.BaseDirectory + @"Download\alipay_" + date + @".csv\20881319318318420156_" + date + "_业务明细.csv";
                    DataTable datajson = PayHelp.CsvRead(4, ms);//读取excel表中数据

                    string tradeNoStr = "";
                    for (int i = 0; i < datajson.Rows.Count; i++)
                    {

                        string tradeNo = datajson.Rows[i]["商户订单号"].ToString().Trim();
                        if (tradeNo.IndexOf("20") != -1)
                        {
                            if (tradeNo.Substring(0, 1) == "3")
                            {
                                tradeNoStr += tradeNo + ",";
                            }
                        }
                    }

                    if (tradeNoStr.Length == 0)
                    {
                        textBox7.AppendText("第" + count + "次支付宝对账单没有记录..\n");
                    }
                    else
                    {
                        tradeNoStr = tradeNoStr.Substring(0, tradeNoStr.Length - 1);

                        int c = (tradeNoStr.Split(',').Length);

                        //本地

                        string sql = "select * from t_shop_moneyLog where zt='1' and shopId !='1' and pudate >='" + date + " 00:00:00" + "' and  pudate <='" + date + " 23:59:59" + "' and left(tradeNo,1)='3'";
                        DataTable dt = dal.getDataSet(sql).Tables[0];
                        int bdCount = 0;
                        if (dt != null)
                        {
                            bdCount = dt.Rows.Count;
                        }

                        //记录对不上 报警
                        if (c != bdCount)
                        {
                            textBox7.AppendText("第" + count + "次支付宝对账记录不一致..已发短信\n");
                            //发短信
                            SendSimMessage("13299021002", "检测到昨日百富支付宝支付记录与系统不一致！");
                            SendSimMessage("13989767654", "检测到昨日百富支付宝支付记录与系统不一致！");
                            SendMessage("100010", "支付宝对账不正常", "检测到昨日百富支付宝支付记录与系统不一致！");
                            SendMessage("100002", "支付宝对账不正常", "检测到昨日百富支付宝支付记录与系统不一致！");
                        }
                        else
                        {
                            textBox7.AppendText("第" + count + "次支付宝对账记录一致..\n");
                        }

                    }

                    #endregion
                }
                else
                {
                    textBox7.AppendText("第" + count + "次支付宝对账异常..\n");
                    //发短信
                    SendSimMessage("13299021002", "百富支付宝对账监控异常，请手动查询昨日记录！");
                    SendSimMessage("13989767654", "百富支付宝对账监控异常，请手动查询昨日记录！");
                    SendMessage("100010", "支付宝对账异常", "百富支付宝对账监控异常，请手动查询昨日记录！");
                    SendMessage("100002", "支付宝对账异常", "百富支付宝对账监控异常，请手动查询昨日记录！");
                }
            }
            else
            {
                textBox7.AppendText("第" + count + "次支付宝对账出错..\n");
                //发短信
                SendSimMessage("13299021002", "百富支付宝对账监控出错，请手动查询昨日记录！");
                SendSimMessage("13989767654", "百富支付宝对账监控出错，请手动查询昨日记录！");
                SendMessage("100010", "支付宝对账出错", "百富支付宝对账监控出错，请手动查询昨日记录！");
                SendMessage("100002", "支付宝对账出错", "百富支付宝对账监控出错，请手动查询昨日记录！");
            }
        }

      
    }
}
